package com.wzy.alllearning.util;


import java.util.Set;

import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;

import org.springframework.util.CollectionUtils;

/**
 * 手动参数校验
 */
public class ValidatorUtils
{
	private static Validator validator = Validation.buildDefaultValidatorFactory().getValidator();

	public static <T> void validate(T object, Class... groups)
	{
		Set<ConstraintViolation<T>> validateSet = validator.validate(object, groups);

		if (CollectionUtils.isEmpty(validateSet))
		{
			StringBuilder exceptionMessage = new StringBuilder();
			validateSet.forEach(constraintViolation ->
			{
				exceptionMessage.append(constraintViolation.getMessage());
			});
			throw new RuntimeException(exceptionMessage.toString());
		}
	}
}
